package com.share.thread;

/**
 * @desc:
 * @author:caifan
 * @date:2022/1/19
 */
public class TakeTurns {

    public static void main(String[] args) {
        Print print = new Print();
        Thread t1 = new Thread(() -> {
            try {
                print.print1();
            } catch (Exception e) {

            }
        });

        Thread t2 = new Thread(() -> {
            try {
                print.print2();
            } catch (Exception e) {

            }
        });
        t1.start();
        t2.start();

    }
}

class Print {
    private volatile boolean flag = true;

    private static int count = 0;

    public synchronized void print1() throws Exception {

        for (int i = 1; i <= 50; i++) {
            while (flag) {
                wait();
            }
            System.out.println("print1:" + ++count);
            flag = !flag;
            notifyAll();
        }
    }

    public synchronized void print2() throws Exception {

        for (int i = 1; i <= 50; i++) {
            while (!flag) {
                wait();
            }
            System.out.println("print2:" + ++count);
            flag = !flag;
            notifyAll();
        }
    }
}
